
#include "calServer.hpp"


#include <memory>

using namespace Server;
// 提示 运行格式
static void Usage(string proc)
{
    cout<<"Usage:\n\t" << proc <<" local_port\n\n";
}
// 计算客户端发来的任务
// req：里面是一个处理好的完整的请求对象
// resp：根据req进行业务处理，填充resp，不用管理任何读取和写入，序列化和反序列化等细节，在这之前已经处理好了
bool cal(const Request& req,Response& resp)
{
    // req 里已经有结构化的数据了，直接使用即可
    resp._exitcode = OK;
    resp._result = OK;
    switch(req._op)
    {
        case '+':
            resp._result = req._x + req._y;
            break;
        case '-':
            resp._result = req._x - req._y;
            break;
        case '*':
            resp._result = req._x * req._y;
            break;
        case '/':
        {
            if(req._y == 0) 
                resp._exitcode = DEV_ZERO;
            else 
                resp._result = req._x / req._y;
        }
            break;    
        case '%':
        {
            if(req._y == 0) 
                resp._exitcode = MOD_ZERO;
            else 
                resp._result = req._x % req._y;
        }
            break;  
        default:
            resp._exitcode = OP_ERROR;
            break;                      
    }
    return true;
}

// ./calServer local_port
int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    unique_ptr<calServer> tsvr(new calServer(port));
    tsvr->initServer();
    tsvr->start(cal);

    return 0;
}